Skip to content

Type min() / max() of two arguments as the union of both comparison orders - #7050

Merged
staabm merged 6 commits into
phpstan:2.3.xfrom
zonuexe:minmax-nan-both-orders
Nov 13, 2026
Merged

staabm merged 6 commits into
phpstan:2.3.xfrom
zonuexe:minmax-nan-both-orders

Conversation

@zonuexe

@zonuexe zonuexe commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

MinMaxFunctionReturnTypeExtension types min($a, $b) as $a < $b ? $a : $b and max($a, $b) as $a < $b ? $b : $a. When the arguments compare as equal or one of them is NAN, which argument PHP returns depends on the PHP version and on how the call was compiled. This PR types both calls as the union of the two orders PHP uses.

Impact

Since float ranges (#6937), the comparison in the rewrite narrows floats, so picking one order drops values that PHP can return.

Expression ($f is float) Before After
max(0.0, $f) float<0.0, max> NAN|float<0.0, max>
min($f, 1.0) float<min, 1.0> NAN|float<min, 1.0>
max(0.0, min(1.0, $f)) float<0.0, 1.0> NAN|float<0.0, 1.0>
max(1, NAN) 1 1|NAN
min(0, 0.0) 0.0 0|0.0
max(0, 0.0) 0 0
  • PHPStan reported is_nan(max(0.0, $f)) as always false. It is true for NAN on PHP 7.4 to 8.2, 8.4 and 8.5.
  • PHPStan reported is_nan(\max(0.0, \min(1.0, $f))) as always false. It is true for NAN for a direct call on PHP 8.4 and 8.5.
  • PHPStan reported \min($n, 100) === 100.0 with int|float $n as always false. It is true for 100.0 on PHP 7.4 to 8.3.
  • Two integers, two float ranges that cannot be NAN (float<min, max>, or after !is_nan($f)) and max() of equal values keep their current types. min() of a float and an integer that can be equal gains the other argument, like min(0, 0.0).
  • Before Add FloatRangeType for float<min, max> #6937 the float rows were float. The rows with constants predate Add FloatRangeType for float<min, max> #6937.

I found this while comparing #6937 with a FloatRangeType prototype I had been working on before it landed. My own review of that prototype had flagged the same max() rewrite.

Cause

PHP has two implementations of min() and max() with two arguments: the function itself and, since PHP 8.4, a frameless handler. The function also changed in PHP 8.3. They agree unless the arguments compare as equal or cannot be ordered.

7.4 – 8.2 8.3 8.4+, function 8.4+, frameless
max(0.0, NAN) NAN 0.0 0.0 NAN
max(NAN, 0.0) 0.0 NAN NAN 0.0
min(0.0, NAN) 0.0 0.0 0.0 NAN
min(NAN, 0.0) NAN NAN NAN 0.0
min(0, 0.0) 0 0 0 0.0
max(0, 0.0) 0 0 0 0

Measured on 7.4.33, 8.0.30, 8.1.34, 8.2.35, 8.3.36, 8.4.27 and 8.5.12.

  • PHP 8.4+ uses the frameless handler for a direct call with two arguments. It uses the function for call_user_func('max', …), array_map('max', …) and max(...$args), which this extension types too.
  • A direct call does not always compile to the frameless handler. With Xdebug 3.5.3 in develop mode, \max(0.0, NAN) is 0.0 on PHP 8.5.12. Inside a namespace, max(0.0, min(1.0, NAN)) without imports is 1.0, while \max(0.0, \min(1.0, NAN)) is NAN.
  • The existing rewrite of min() is the one the frameless handler uses. The one of max() matches the function since PHP 8.3 for integers and floats. Neither holds for every call.
  • max/min return wrong value if signed (negative) zero php/php-src#20221 (signed zero in min() / max()) covers the frameless min() returning the second of two equal values. It does not cover NAN.

Fix

For two arguments that cannot be arrays, the extension now returns the union of both rewrites: $a < $b ? $a : $b and $b < $a ? $b : $a for min(), and $a < $b ? $b : $a and $a >= $b ? $a : $b for max(). When both arguments are integers the two rewrites give the same values, so it evaluates only the first one.

I did not make it depend on the PHP version. PHP 8.3 and older have one implementation per version, so a version check could type them exactly, and max(0.0, min(1.0, $f)) would stay float<0.0, 1.0> there. max() would need a different rewrite up to 8.2 and on 8.3. I can add that if you prefer it.

Other sites

  • min() / max() with three or more arguments, a single array or an unpacked array go through processType(). For scalar arguments it returns the union of the arguments unless they are constants that order strictly, so it does not drop NAN. This PR does not touch it.
  • processType() still picks one side for constant arrays whose elements cannot be ordered. max([[NAN, 1], [0.0, 2]]) is typed array{0.0, 2}, and PHP 7.4 to 8.5 return [NAN, 1]. This is older than Add FloatRangeType for float<min, max> #6937 and not part of this PR.

Testing

tests/PHPStan/Analyser/nsrt/minmax-nan.php covers NAN on either side, float ranges with and without NAN, equal values of different types, integer ranges, call_user_func() and array_map(). Without the change, 26 of its assertions fail.

Before After
minmax-nan.php 26 assertions fail passes
make tests n/a 23715 tests, no failures (74 skipped)
make tests with the turbo extension loaded n/a 23715 tests, no failures (74 skipped)
make phpstan n/a no errors

The benchmarks in tests/bench/data do not call min() or max().

@staabm

staabm commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

//cc @SanderMuller

@staabm

staabm commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

as I read the PR description, before this PR we have unexpected errors for this cases:

  • PHPStan reported is_nan(max(0.0, $f)) as always false. It is true for NAN on PHP 7.4 to 8.2, 8.4 and 8.5.

  • PHPStan reported is_nan(\max(0.0, \min(1.0, $f))) as always false. It is true for NAN for a direct call on PHP 8.4 and 8.5.

  • PHPStan reported \min($n, 100) === 100.0 with int|float $n as always false. It is true for 100.0 on PHP 7.4 to 8.3.

if this is fixed now, we need tests for them

@zonuexe

zonuexe commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Added the three cases as rule tests, ImpossibleCheckTypeFunctionCallRuleTest::testMinMaxNan() and StrictComparisonOfDifferentTypesRuleTest::testMinMaxNan(). Both fail on the base commit with the errors from the description and pass now.

@staabm

staabm commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

max(0.0, $f) float<0.0, max> NAN|float<0.0, max>

do we also need to think about INF?

https://3v4l.org/A3Rc1#veol

@zonuexe

zonuexe commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

PHP's behaviour across versions for the table above: https://3v4l.org/tVFpJ

@zonuexe

zonuexe commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

No, INF is covered. max in float<0.0, max> is INF, so the range includes it, and max(0.0, INF) is INF on every version, as in your 3v4l. The float<0.0, max> in the table is the type PHPStan infers for the value, so only NAN was missing.

@SanderMuller SanderMuller left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I compared the types with real PHP 7.4 and 8.0 to 8.5 on 722 calls: min() and max() of every pair of 19 constants. The constants are ints, floats including -0.0, NAN, INF and -INF, numeric and non-numeric strings, bools and null. For each version I ran four forms: the direct call in the global namespace, \max() and max() in a namespace, and call_user_func(). Then I checked that every result is in the type for that phpVersion.

  • On 2.3.x, 120 to 147 calls per version get a type that does not contain the real result. For example, min(0, 0.0) is 0.0 where PHP returns 0. With this PR it is 3 to 8.
  • On 7.4 to 8.3 the four forms give the same result for every call. On 8.4 and 8.5, 134 direct calls differ from call_user_func(), and the three direct forms agree with each other. This supports your note that a version check could type 8.3 and older exactly.

Two cases still lose a value. Both are also wrong on 2.3.x:

  • max(NAN, -1) is NAN, but PHP 7.4 to 8.2 return -1, and so does a direct call on 8.4 and 8.5. max(-1, NAN) is NAN (*NEVER* on 2.3.x), but PHP 8.3 returns -1, and so does call_user_func() on 8.4 and 8.5. With 0 in place of -1, both calls give 0|NAN.
  • max(-1, '') and max('', -1) are *NEVER* with phpVersion 8.0 to 8.5. PHP returns -1.

The comparisons themselves are typed correctly: NAN >= -1 ? NAN : -1 is -1, and -1 >= '' is true. So the value gets lost in the rewrite with AlwaysRememberedExpr, not in the comparison. I did not find the exact place.

The only other differences are min() of -0.0 with false or null, in either order. They give 0.0|false and 0.0|null where PHP can return -0.0. As -0.0 === 0.0, that only affects the description.

With a float $f, max(-1, $f) is -1|NAN|float<-0.9999999999999999, max> and max($f, -1) is -1|NAN|float<-1.0, max>. Both are correct.

minmax-nan.php and both testMinMaxNan() rule tests fail without the change in the extension and pass with it. On de379c9 the full test suite, make phpstan and phpcs pass. The five red CI jobs are also red on the base commit, or on #6539 and #7038.

Performance: the extra rewrite has a cost. I generated a file with 400 functions, each with seven min() / max() calls of two arguments. I analysed it at level 8 in two rounds of 8 runs per side.

  • The median is 6.28 s on 2.3.x and 7.39 s with this PR.
  • User CPU is 4.50 s against 5.53 s in the second round, and 4.65 s against 5.56 s in the first.
  • That is about 0.4 ms of CPU for each of the 2,400 calls that do not have two integer arguments.
  • The cost does not grow with nesting: min() / max() nested 4 to 10 deep take 3.0 s on both sides.

@zonuexe

zonuexe commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the matrix. Both remaining cases had one cause: the comparison narrowed an operand written as a constant expression such as -1, so NAN >= -1 ? NAN : -1 turned -1 into never. The comparison now uses the constant's type for constant arguments, and the branches keep the original expressions. max(NAN, -1), max(-1, NAN), min(NAN, -1) and min(-1, NAN) are -1|NAN, and max(-1, '') and max('', -1) are -1. I added the NAN cases to minmax-nan.php and left the string cases out of it, because PHP 7.4 returns a different value for them.

@SanderMuller

Copy link
Copy Markdown
Contributor

Thanks. I ran the grid again on 7ce253f. Now every type contains the real result on 7.4 to 8.5, also for the -0.0 cases.

Two things I found with variables:

  • isConstantScalarValue() is also true for a union of constants, so such an argument is no longer narrowed. With @param 1|10 $x, max($x, 5) and min($x, 5) are now both 1|5|10. On 2.3.x and on de379c9 they are 5|10 and 1|5.
  • A non-constant argument next to NAN still loses values, as on 2.3.x. With int<-5, -1> $r, max(NAN, $r) is NAN. For $r = -3, PHP 7.4 to 8.2 return -3, and so does a direct call on 8.4 and 8.5. With int $i, max(NAN, $i) is NAN|int<1, max>. On the same versions PHP returns -3 for $i = -3 and 0 for $i = 0.

I think the cause is the narrowing by a comparison with NAN, which also happens outside min() and max(). On 2.3.x, with @param -1|-2 $n:

if (NAN >= $n) { /* $n is -2|-1 */ } else { /* $n is *NEVER* */ }
if ($n < NAN) { /* *NEVER* */ } else { /* *NEVER* */ }

In PHP both comparisons are false for every $n. With int $i, NAN >= $i narrows $i to int<min, 0> and int<1, max>. If that narrowing is fixed, the TypeExpr change might not be necessary, but I did not try it.

The min/max nsrt tests and both comparison rule tests pass on 7ce253f. I did not run the full suite or the benchmark again.

@zonuexe

zonuexe commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Good catch, that was my regression. I dropped TypeExpr and instead keep a literal argument out of AlwaysRememberedExpr: BinaryOpHandler already skips narrowing for a Scalar and for a UnaryMinus of one, and the wrapper hid that from it. An argument whose type is a union of constants is a variable, so it is narrowed again: max($x, 5) is 5|10 and min($x, 5) is 1|5, and the NAN cases stay -1|NAN. I added the 1|10 case to minmax-nan.php. The full suite and make phpstan pass.

I agree about the cause of the second one, and it is phpstan/phpstan#15713: in the false branch of a comparison, BinaryOpHandler narrows a side without checking that the other side cannot be NAN. I would rather fix that there than in this extension, since it also needs the change in the turbo mirror. Then max(NAN, $r) follows from the comparison, as it already does for the literals.

…rders

MinMaxFunctionReturnTypeExtension typed min($a, $b) as $a < $b ? $a : $b
and max($a, $b) as $a < $b ? $b : $a. Which argument PHP returns when
the two compare as equal or one of them is NAN depends on the PHP
version and on how the call was compiled. PHP 8.4 added a frameless
handler for direct calls, which disagrees with the function body that
call_user_func(), array_map() and unpacked calls use. A direct call
also falls back to the function body under Xdebug and for unqualified
nested calls inside a namespace. PHPStan cannot tell these apart.

Since float ranges, the comparison in the rewrite narrows floats, so
picking one order dropped values PHP returns: max(0.0, $float) was
float<0.0, max> although max(0.0, NAN) is NAN on PHP 7.4 to 8.2 and for
direct calls on 8.4+. Regardless of float ranges, min(0, 0.0) was 0.0
although it is 0 on PHP 8.3 and older.

For two arguments that cannot be arrays, return the union of both
rewrites: $a < $b ? $a : $b and $b < $a ? $b : $a for min(), and
$a < $b ? $b : $a and $a >= $b ? $a : $b for max(). Integers are totally
ordered and equal integers are the same value, so for two integers the
first rewrite is enough.
… rules

Kill the mutants of the integer shortcut in MinMaxFunctionReturnTypeExtension.
…n the rewrite

The comparison with NAN narrowed a constant such as -1 to never in the branch that returns it.
Narrowing skips literals, so a comparison with NAN no longer turns one into never, and an argument whose type is a union of constants is narrowed again.
@staabm
staabm force-pushed the minmax-nan-both-orders branch from 3997266 to 14e39d6 Compare November 13, 2026 15:06
@staabm

staabm commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

@SanderMuller any more input/edge-cases? :)

@SanderMuller

Copy link
Copy Markdown
Contributor

One more. The 1|10 case is fixed, and the literal grid is still sound on 7.4 to 8.5. But a constant that is not a literal in the code goes through AlwaysRememberedExpr again. With class K { const NEG = -1; }:

  • max(NAN, K::NEG) is NAN. PHP 7.4, 8.0 and 8.5 return -1, and 7ce253f gave -1|NAN.
  • max(K::NEG, '') is *NEVER*. PHP 8 returns -1, and 7ce253f gave -1.

With a global const NEG = -1 or with +-1, max(NAN, …) is also NAN. On 2.3.x, max(NAN, K::NEG) and max(K::NEG, '') are NAN and *NEVER* as well.

Deciding by the type instead of the node fixes both for me:

if (count($type->getConstantScalarValues()) === 1) {
	return new TypeExpr($type);
}

A single value cannot be narrowed anyway, and a union of constants still gets AlwaysRememberedExpr. With this change, max($x, 5) is 5|10 again, all the constant calls above match 7ce253f, and the grid stays sound. The min/max nsrt tests and both testMinMaxNan() rule tests pass. I did not run the full suite.

…node

A constant that is not written as a literal, such as a class constant, went through AlwaysRememberedExpr and the comparison with NAN narrowed it to never.
@staabm
staabm merged commit 94519e2 into phpstan:2.3.x Nov 13, 2026
885 of 894 checks passed
@staabm

staabm commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Thank you!

If there is still something left, please open new issues

@zonuexe

zonuexe commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for all the verification on this one, and sorry for the late reply — it was merged as 94519e2 before I got back to it. I took the getConstantScalarValues() check as you wrote it; deciding by the type is better than my node check, since it covers a class constant, a global constant and +-1 without listing node kinds.

I fixed the remaining case in #7058: BinaryOpHandler narrowed a side of an ordering comparison in the false branch without checking that the other side cannot be NAN, which is phpstan/phpstan#15713. max(NAN, $r) with int<-5, -1> is now NAN|int<-5, -1>, and max(NAN, $i) with int is NAN|int. The same assumption of a total order was in the rewrite of a count() comparison, so that is in there too. No existing test expectation moved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants